package com.symbio.ishenapi.background.controller;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.background.model.*;
import com.symbio.ishenapi.background.model.base.PersonScheduling;
import com.symbio.ishenapi.background.util.util;
import com.symbio.ishenapi.common.bean.LoginUser;
import com.symbio.ishenapi.common.bean.QueryModel;
import com.symbio.ishenapi.common.controller.BaseController;
import io.jboot.web.controller.annotation.RequestMapping;
import org.apache.curator.shaded.com.google.common.collect.Lists;
import org.apache.curator.shaded.com.google.common.collect.Maps;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 排班
 */
@RequestMapping("/tmSchedulingController")
public class TmSchedulingController extends BaseController {

    /**
     * 保存排班信息和时间段信息
     */
    public  void save(){
        String doctorId = getPara("doctorId");//医生id
        // String schedulingType = getPara("schedulingType");//排班类型
        String schedulingTime = getPara("schedulingTime");//排班日期
        String statusTime = getPara("statusTime");//开始时间
        String endTime = getPara("endTime");//结束时间

        TmScheduling tmScheduling = TmScheduling.dao.findBydoctorId(doctorId,schedulingTime);//查询排班信息
        List<TmSchedulingRecord> list =  null;
        if(tmScheduling != null){
            list = TmSchedulingRecord.dao.findListBySchedulingId(tmScheduling.getId());//查询排班时间段信息
        }else{
            list = new ArrayList<TmSchedulingRecord>();
        }
        TmScheduling tm = new TmScheduling();//创建新的对象
        // SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
        //判断排班信息是否有数据，没有存一条，有了不存直接存时间段信息
        if(tmScheduling == null){//判断根据id查询信息是否是空
            BigInteger did = new BigInteger(doctorId);
            tm.setDoctorId(did);
            tm.setSchedulingType(0L);
            //String转date
            Date date = util.strToDate(schedulingTime);
            tm.setSchedulingTime(date);
            tm.setStatus(1L);
            tm.setCreateTime(new Date());
            if(tm.save()) {//保存排班信息
                if(list == null || list.size() <= 0){
                    TmSchedulingRecord tsr = new TmSchedulingRecord();
                    tsr.setStatusTime(statusTime);
                    tsr.setEndTime(endTime);
                    tsr.setSchedulingId(tm.getId());
                    tsr.setStatus(1L);
                    tsr.setCreateTime(new Date());
                    //保存排班时间段信息
                    if(tsr.save()){
                        renderJsonRet(40001);
                        return;
                    }else{
                        renderJsonError(40002);
                        return;
                    }
                }else{
                    int flag = 0;//0表示冲突
                    for (TmSchedulingRecord tmSchedulingRecord : list) {
                        Date tstatusTime = util.strToDateLong(tmSchedulingRecord.getStatusTime());//这是从库里查出来的开始时间
                        Date tendTime = util.strToDateLong(tmSchedulingRecord.getEndTime());//这是从库里查出来的结束时间
                        Date newStatusTime = util.strToDateLong(statusTime);//这个是传进来的开始时间
                        Date newEndTime = util.strToDateLong(endTime);//这个是传进来的开结束时间
                        System.out.println(tstatusTime.getTime() + "====================" + tendTime.getTime() + "+++++++++++" + newEndTime);
                        //判断时间段是否可以存
                        if (newStatusTime.getTime() >= tendTime.getTime() || newEndTime.getTime() <= tstatusTime.getTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                            break;
                        }

                    }
                    if(flag == 0){
                        renderJsonError(40017,"医生排班");
                        return;
                    }else{
                        BigInteger id = tmScheduling.getId();//排班主键id
                        TmSchedulingRecord tsr = new TmSchedulingRecord();
                        tsr.setStatusTime(statusTime);
                        tsr.setEndTime(endTime);
                        tsr.setSchedulingId(id);
                        tsr.setStatus(1L);
                        tsr.setCreateTime(new Date());
                        //保存排班时间段信息
                        if(tsr.save()){
                            renderJsonRet(40001);
                            return;
                        }else{
                            renderJsonError(40002);
                            return;
                        }
                    }
                }
            }
        }else{//这只存时间段信息
            if(list != null && list.size() > 0){
                int flag = 0;//0表示冲突
                if(list != null || list.size() > 0) {
                    for (TmSchedulingRecord tmSchedulingRecord : list) {
                        Date tstatusTime = util.strToDateLong(tmSchedulingRecord.getStatusTime());//这是从库里查出来的开始时间
                        Date tendTime = util.strToDateLong(tmSchedulingRecord.getEndTime());//这是从库里查出来的结束时间
                        Date newStatusTime = util.strToDateLong(statusTime);//这个是传进来的开始时间
                        Date newEndTime = util.strToDateLong(endTime);//这个是传进来的开结束时间
                        System.out.println(tstatusTime.getTime() + "====================" + tendTime.getTime() + "+++++++++++" + newEndTime);
                        //判断时间段是否可以存
                        if (newStatusTime.getTime() >= tendTime.getTime() || newEndTime.getTime() <= tstatusTime.getTime()) {
                            flag = 1;
                        } else {
                            flag = 0;
                            break;
                        }

                    }
                }else{
                    flag = 1;
                }
                if(flag == 0){
                    renderJsonError(40017,"医生排班");
                    return;
                }else{
                    BigInteger id = tmScheduling.getId();//排班主键id
                    TmSchedulingRecord tsr = new TmSchedulingRecord();
                    tsr.setStatusTime(statusTime);
                    tsr.setEndTime(endTime);
                    tsr.setSchedulingId(id);
                    tsr.setStatus(1L);
                    tsr.setCreateTime(new Date());
                    //保存排班时间段信息
                    if(tsr.save()){
                        renderJsonRet(40001);
                        return;
                    }else{
                        renderJsonError(40002);
                        return;
                    }
                }
            }else{
                BigInteger id = tmScheduling.getId();//排班主键id
                TmSchedulingRecord tsr = new TmSchedulingRecord();
                tsr.setStatusTime(statusTime);
                tsr.setEndTime(endTime);
                tsr.setSchedulingId(id);
                tsr.setStatus(1L);
                tsr.setCreateTime(new Date());
                //保存排班时间段信息
                if(tsr.save()){
                    renderJsonRet(40001);
                    return;
                }else{
                    renderJsonError(40002);
                    return;
                }
            }

        }

    }



    /**
     * 根据id获取排班信息
     */
    public void findById() {
        TmScheduling user = (TmScheduling) getReqBodyObject(TmScheduling.class);
        TmScheduling tmScheduling = TmScheduling.dao.findById(user.getId());
        if (tmScheduling != null) {
            renderJsonRet(tmScheduling);
        } else {
            renderJsonError(40003);
            return;
        }
    }

    /**
     *返回日历图数据,返回单个医生的排班
     */
    public void personList() {
        String year = getPara("year");
        int months = getParaToInt("month");
        // String schedulingId = getPara("schedulingId");
        BigInteger doctorId = new BigInteger(getPara("doctorId"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        // 开始时间
        String month = months < 10 ? "0" + months : months + "";
        String startDate = year + "-" + month + "-01";
        Date sDate = null;
        try {
            sDate = sdf.parse(startDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(sDate);
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int preDays = week - 1;
        cal.add(Calendar.DAY_OF_YEAR, -1 * preDays);
        sDate = cal.getTime();

        // 结束时间
        Date temp = null;
        try {
            temp = sdf.parse(year + "-" + month + "-01");
        } catch (Exception e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(temp);
        String endDate = year + "-" + month + "-" + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + "";
        Date eDate = null;
        try {
            eDate = sdf.parse(endDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(eDate);
        week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int sufDays = 7 - week;
        cal.add(Calendar.DAY_OF_YEAR, sufDays);
        eDate = cal.getTime();
        renderJsonRet(convert(sDate,eDate,months,doctorId,false));
    }


    /**
     * 封装数据
     * @param start
     * @param end
     * @param currentMonth
     * @param userId
     * @param isExchange
     * @return
     */
    private List<PersonScheduling> convert(Date start, Date end, int currentMonth, BigInteger userId, boolean isExchange) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(start);//开始时间
        String e = sdf.format(end);//结束时间
        List<TmScheduling> rets = TmScheduling.dao.selectByDocor(s,e, userId);

        Map<String, TmScheduling> map = Maps.newHashMap();
        for (TmScheduling ret : rets) {
            map.put(DateKit.toStr(ret.getSchedulingTime(), "yyyy-MM-dd"), ret);
        }
        List<PersonScheduling> ret = Lists.newArrayList();
        cal.setTime(start);

        while (true) {
            if (cal.getTime().getTime() > end.getTime()) {
                break;
            }
            PersonScheduling personScheduling = new PersonScheduling();
            String yearStr = cal.get(Calendar.YEAR)+"";//获取年份
            int month = cal.get(Calendar.MONTH) + 1;//获取月份
            String monthStr = month < 10 ? "0" + month : month + "";
            int day = cal.get(Calendar.DATE);//获取日
            String dayStr = day < 10 ? "0" + day : day + "";
            String da = yearStr+"-"+month+"-"+dayStr;
            personScheduling.setYmd(da);
            personScheduling.setDay(cal.get(Calendar.DAY_OF_MONTH));
            personScheduling.setMonth(currentMonth);
            if (cal.get(Calendar.MONTH) + 1 == currentMonth) {
                personScheduling.setCurrentMonth(true);
            } else {
                personScheduling.setCurrentMonth(false);
            }
            Long i = 1L;
            personScheduling.setId(i++);
            ret.add(personScheduling);
            cal.add(Calendar.DAY_OF_YEAR, 1);
        }
        for(int i = 0;i< ret.size();i++){
            for(int j=0;j<rets.size();j++){
                String statusDate =  sdf.format(rets.get(j).getSchedulingTime());
                String []str = statusDate.split("-");
                int day = Integer.parseInt(str[2]);

                if(ret.get(i).getYmd().equals(statusDate)){
                    List<TmSchedulingRecord> list = TmSchedulingRecord.dao.findListBySchedulingId(rets.get(j).getId());
                    if(ret.get(i).getDay() == day){
                        if(list != null && list.size() > 0){
                            ret.get(i).setRecordList(list);
                        }


                    }else{
                            list = new ArrayList<TmSchedulingRecord>();
                            ret.get(i).setTmSchedulingRecordList(null);
                        }
                }

            }
        }
        return ret;
    }


    /**
     *
     * 查询保险团全部成员的排班
     *
     */
    public void personSchedulingList() {
        String year = getPara("year");
        int months = getParaToInt("month");
        // String schedulingId = getPara("schedulingId");
        BigInteger scheduingId = new BigInteger(getPara("scheduingId"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();

        // 开始时间
        String month = months < 10 ? "0" + months : months + "";
        String startDate = year + "-" + month + "-01";
        Date sDate = null;
        try {
            sDate = sdf.parse(startDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(sDate);
        int week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int preDays = week - 1;
        cal.add(Calendar.DAY_OF_YEAR, -1 * preDays);
        sDate = cal.getTime();

        // 结束时间
        Date temp = null;
        try {
            temp = sdf.parse(year + "-" + month + "-01");
        } catch (Exception e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(temp);
        String endDate = year + "-" + month + "-" + cal.getActualMaximum(Calendar.DAY_OF_MONTH) + "";
        Date eDate = null;
        try {
            eDate = sdf.parse(endDate);
        } catch (ParseException e) {
            renderJsonError(40008);
            return;
        }
        cal.setTime(eDate);
        week = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week == 0) {
            week = 7;
        }
        int sufDays = 7 - week;
        cal.add(Calendar.DAY_OF_YEAR, sufDays);
        eDate = cal.getTime();
        renderJsonRet(convertAll(sDate,eDate,months,scheduingId,false));
    }


    /**
     * 查询保险团全部成员排班信息
     * @param start
     * @param end
     * @param currentMonth
     * @param userId
     * @param isExchange
     * @return
     */
    private List<PersonScheduling> convertAll(Date start, Date end, int currentMonth, BigInteger userId, boolean isExchange) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(start);//开始时间
        String e = sdf.format(end);//结束时间
        List<TmDoctorInsuranceCorps> tdicList = TmDoctorInsuranceCorps.dao.findList(userId.toString());


           /* Map<String, TmScheduling> map = Maps.newHashMap();
            for (TmScheduling ret : rets) {
                map.put(DateKit.toStr(ret.getSchedulingTime(), "yyyy-MM-dd"), ret);
            }*/
            List<PersonScheduling> ret = Lists.newArrayList();
            cal.setTime(start);
            while (true) {
                if (cal.getTime().getTime() > end.getTime()) {
                    break;
                }
                PersonScheduling personScheduling = new PersonScheduling();
                String yearStr = cal.get(Calendar.YEAR) + "";//获取年份
                int month = cal.get(Calendar.MONTH) + 1;//获取月份
                String monthStr = month < 10 ? "0" + month : month + "";
                int day = cal.get(Calendar.DATE);//获取日
                String dayStr = day < 10 ? "0" + day : day + "";
                String da = yearStr + "-" + month + "-" + dayStr;
                personScheduling.setYmd(da);
                personScheduling.setDay(cal.get(Calendar.DAY_OF_MONTH));
                personScheduling.setMonth(currentMonth);
                if (cal.get(Calendar.MONTH) + 1 == currentMonth) {
                    personScheduling.setCurrentMonth(true);
                } else {
                    personScheduling.setCurrentMonth(false);
                }
                Long j = 1L;
                personScheduling.setId(j++);
                ret.add(personScheduling);
                cal.add(Calendar.DAY_OF_YEAR, 1);
            }

            for (int i = 0; i < ret.size(); i++) {
                List<List<Map<String,String>>> tList = new ArrayList<>();
                for(int k = 0;k < tdicList.size();k++) {
                    List<TmScheduling> rets = TmScheduling.dao.selectByDocor(s, e, tdicList.get(k).getDoctorId());
                    TmDoctorUser doctorUser = TmDoctorUser.dao.getById(tdicList.get(k).getDoctorId().toString());
                        for (int j = 0; j < rets.size(); j++) {
                            String statusDate = sdf.format(rets.get(j).getSchedulingTime());
                            String[] str = statusDate.split("-");
                            int day = Integer.parseInt(str[2]);

                            if (ret.get(i).getYmd().equals(statusDate)) {
                                List<TmSchedulingRecord> list = TmSchedulingRecord.dao.findListBySchedulingId(rets.get(j).getId());
                                if (ret.get(i).getDay() == day) {
                                    if (list != null && list.size() > 0) {
                                        //ret.get(i).setRecordList(list);
                                        List<Map<String,String>> listMap = new ArrayList<>();
                                        for(int n = 0;n<list.size();n++){
                                            Map<String,String> map = new HashMap();
                                            map.put("userName",doctorUser.getUserName());
                                            map.put("statusTime",list.get(n).getStatusTime());
                                            map.put("endTime",list.get(n).getEndTime());
                                            listMap.add(map);

                                        }
                                        tList.add(listMap);
                                       //
                                    }
                                }
                            }
                            System.out.println(tList);
                           //
                        }
                    ret.get(i).setTmSchedulingRecordList(tList);
            }
                    ret.get(i).setTmSchedulingRecordList(tList);
        }
        return ret;

    }

    /**
     * @Author jianghy
     * @Description 排班列表查询
     * @date
     * @return void
     */
    public void querySchedulingList(){
        String userPN = getPara("userPN");
        if(userPN==null)
            userPN="%";

        LoginUser loginUser = getLoginUser();
        String Ids = loginUser.getDoctorIds();
        if (Ids.endsWith(",")) {
            Ids = Ids.substring(0,(Ids.length() - 1));
        }
        Map map = TmScheduling.dao.findAllSchedulingDoctor(getQueryModel(),userPN,Ids);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }
    /**
     * @Author jianghy
     * @Description 医生排班删除及批量删除
     * @date
     * @return void
     */
    public void deleteDoctorSchedulsing(){
        String schedulingId = getPara("schedulingId");
        try{
            int count = TmScheduling.dao.deleteDoctorSchedulsing(schedulingId);
            if(count==1)
                renderJsonRet(40021);
            else
                renderJsonRet(40020);
        }catch (Exception e){
            renderJsonError(40009,"排班信息删除");
        }
    }
    /**
     * @Author jianghy
     * @Description 医生停诊及批量停诊
     * @date
     * @return void
     */
    public void stopDoctorStateVisits(){
        String schedulingId = getPara("schedulingId");
        try{
            int count = TmScheduling.dao.stopDoctorStateVisits(schedulingId);
            if(count==1)
                renderJsonRet(40001);
            else
                renderJsonRet(40002);
        }catch (Exception e){
            renderJsonRet(40002);
        }

    }
    /**
     * @Author jianghy
     * @Description 医生复诊
     * @date
     * @return void
     */
    public void startDoctorStateVisits(){
        String schedulingId = getPara("schedulingId");
        try{
            int count = TmScheduling.dao.startDoctorStateVisits(schedulingId);
            if(count==1)
                renderJsonRet(40001);
            else
                renderJsonRet(40002);
        }catch (Exception e){
            renderJsonRet(40002);
        }

    }
    /**
     * @Author jianghy
     * @Description 医生排班信息添加页面列表显示
     * @date
     * @return void
     */
    public void findDoctorList(){
        QueryModel queryModel = getQueryModel();
        String userPN = getPara("userPN");
        int roleId = TmRoleInfo.dao.queryDoctorRoleId();
        List<TmUserRole> listr= TmUserRole.dao.getUserIdByRoleId(roleId);
        StringBuilder sb = new StringBuilder();
        for(int i =0;i<listr.size();i++){
            if(i==listr.size()-1){
                sb.append(listr.get(i).getUserId());
            }else{
                sb.append(listr.get(i).getUserId()+",");
            }
        }
        if(userPN==null||"".equals(userPN)||"null"==userPN)
            userPN="%";
        StringBuilder sb1 = new StringBuilder();
        List<TmScheduling> tlist =  TmScheduling.dao.queryHaveSchedulingDoctors();
        for(int j = 0;j<tlist.size();j++){
            if(j==tlist.size()-1){
                sb1.append(tlist.get(j).getDoctorId());
            }else{
                sb1.append(tlist.get(j).getDoctorId()+",");
            }
        }
        Map map = TmScheduling.dao.findAllDoctor(queryModel,userPN,sb.toString(),sb1.toString());
        renderPageJsonRet(map.get("count"),map.get("data"));
    }
    /**
     * @Author jianghy*
     * @Description 添加医生排班
     * @date
     * @return void
     */
    public void saveSchedulingDoctor(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = new Date();
        try {
            createTime = sdf.parse(sdf.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        TmScheduling tmScheduling = new TmScheduling();
        String doctorId = getPara("doctorId");
        String schedulingType = getPara("schedulingType");//排班类型
        BigInteger docId = new BigInteger(doctorId);
        if(doctorId==null)
            renderJsonError(40009,"添加");
        tmScheduling.setDoctorId(docId);
        tmScheduling.setSchedulingType(new Long(schedulingType));
        tmScheduling.setStatus(new Long(1));
        tmScheduling.setStateVisits(1);
        tmScheduling.setCreateTime(createTime);
        if(tmScheduling.save())
            renderJsonRet(40001);
        else
            renderJsonError(40009,"添加");
    }
    /**
     * @Author jianghy*
     * @Description 医生排班列表点击排班初始化查询 根据排班表id
     * @date
     * @return void
     */
    public void initSchedulingDoctor(){
        String id = getPara("schedulingId");
        List<Record> list = TmScheduling.dao.initSchedulingDoctor(id);
        renderJsonRet(list);
    }
}